#!/usr/bin/env python3

import socketserver
import threading

class EchoTcpHandler(socketserver.StreamRequestHandler):
    """
    The request handler class for Echo Server
    """

    def setup(self):
        super().setup()
        print("{} connected.".format(self.client_address[1]))

    def handle(self):
        try:
            while(True):
                self.data = self.rfile.readline().strip()
                if len(self.data) != 0:
                    print("{} wrote:".format(self.client_address[1]))
                    print(self.data)

                    self.wfile.write(self.data)
                else:
                    break
        except IOError:
            return
        except Exception as e:
            print("Oops! Some things is Wrong", e)

    def finish(self):
        print("{} disconnected.".format(self.client_address[1]))

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

if __name__ =='__main__':
    with ThreadedTCPServer(('localhost', 8080), EchoTcpHandler) as server:
        server_thread = threading.Thread(target=server.serve_forever)
        server_thread.daemon = False
        server_thread.start()
        print("start server forever...")
        import time
        time.sleep(30)
        server.shutdown()
        server.server_close()

        
